import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import {get} from '@/utils/request'
import { Message } from 'element-ui'


const state = {
  token: getToken(),
  userId: '',
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  roleIds: [],
  user:{}
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_USER_ID: (state, userId) => {
    state.userId = userId
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROLE_IDS: (state, roleIds) => {
    state.roleIds = roleIds
  },
  SET_USER:(state,user)=>{
    state.user = user;
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  async getInfo({ commit, state ,dispatch}) {
    // 获取用户基本信息
    let {data} = await getInfo(state.token);
    // 判断用户类型
    if (!data) {
      reject('Verification failed, please Login again.')
    }
    const { realname: name, avatar, introduction, id } = data
    // [{id:1,name:"编辑"},{id:2,name:"管理员"}]
    const roles = data.roles.map(item => item.name)
    const roleIds = data.roles.map(item => item.id)
    commit('SET_ROLE_IDS', roleIds)
    // roles must be a non-empty array
    roles.push('admin')
    if (!roles || roles.length <= 0) {
      reject('getInfo: roles must be a non-null array!')
    }
    commit('SET_USER_ID', id)
    commit('SET_ROLES', roles)
    commit('SET_NAME', name)
    commit('SET_AVATAR', avatar)
    commit('SET_INTRODUCTION', introduction)

    // 加载用户信息
    if(roles.includes('学生')){
      let url = '/student/findByAccountId'
      let {data:student} = await get(url,{id:data.id});
      if(!student){
        // throw new Error("学生信息不存在");
        Message.error("学生信息绑定异常，请联系管理员")
        dispatch("logout")
      }
      data.student = student;
      commit('SET_USER',data)
    } else {
      let url = '/employee/findByAccountId'
      let {data:employee} = await get(url,{id:data.id});
      if(!employee){
        Message.error("员工信息绑定异常，请联系管理员")
        dispatch("logout")
      }
      data.employee = employee;
      commit('SET_USER',data)
    }
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        localStorage.removeItem("studentExam");
        resetRouter()
        dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
